package com.enlf.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * _*_ coding : utf-8 _*_
 *
 * @Time : 2023/9/15 23:08
 * @Author : 计201任思伟
 * @File : IdWork
 * @Project : enjoy-life
 * redis自增
 * ID生成器 与雪花算法类似
 */
@Component
public class IdWork {
    //起始时间
    private static final long START_TEMP=1672531200L;

    //偏移量
    public static final int COUNT_BIT = 32;

    private StringRedisTemplate stringRedisTemplate;

    public IdWork(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public long nextID(String keyPrefix){
        //1.生成31位时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowTime = now.toEpochSecond(ZoneOffset.UTC);
        long timeStamp = nowTime - START_TEMP;
        //2.32位自增序列号
        //2.1获取当前日期 向序列号最后添加
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //2.2自增长
        long serialNum = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);

        return timeStamp << COUNT_BIT | serialNum;
    }

    public static void main(String[] args) {
        //1672531200
        LocalDateTime dateTime = LocalDateTime.of(2023, 1, 1, 0, 0, 0);
        //ZoneOffset.UTC时区
        long time = dateTime.toEpochSecond(ZoneOffset.UTC);
        System.out.println(time);
    }
}
